const storageManager = require('../storage');

/**
 * 数据库表管理工具
 */
module.exports = {
  name: 'database',
  description: '数据库表管理工具，用于添加、查询和列出数据库表结构',
  parameters: {
    type: 'object',
    properties: {
      action: {
        type: 'string',
        enum: ['list', 'add', 'get'],
        description: '要执行的操作: list(列出所有表), add(添加新表), get(获取特定表)'
      },
      name: {
        type: 'string',
        description: '表名称，用于添加或获取表'
      },
      description: {
        type: 'string',
        description: '表描述，用于添加新表'
      },
      ddl: {
        type: 'string',
        description: '表的DDL语句，用于添加新表'
      },
      columns: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            name: { type: 'string' },
            type: { type: 'string' },
            description: { type: 'string' },
            nullable: { type: 'boolean' },
            primaryKey: { type: 'boolean' },
            foreignKey: { type: 'boolean' },
            reference: { type: 'string' }
          }
        },
        description: '表的列定义，用于添加新表'
      },
      indexes: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            name: { type: 'string' },
            columns: { 
              type: 'array',
              items: { type: 'string' }
            },
            unique: { type: 'boolean' }
          }
        },
        description: '表的索引定义，用于添加新表'
      }
    },
    required: ['action']
  },
  handler: async ({ action, name, description, ddl, columns, indexes }) => {
    try {
      switch (action) {
        case 'list':
          const tables = storageManager.getTables();
          return {
            tables,
            count: tables.length
          };
        
        case 'add':
          if (!name) {
            throw new Error('添加表需要提供表名称');
          }
          
          const newTable = storageManager.addTable({
            name,
            description: description || '',
            ddl: ddl || '',
            columns: columns || [],
            indexes: indexes || []
          });
          
          return {
            message: `表 ${name} 添加成功`,
            table: newTable
          };
        
        case 'get':
          if (!name) {
            throw new Error('获取表需要提供表名称');
          }
          
          const tablesList = storageManager.getTables();
          const table = tablesList.find(t => t.name === name);
          
          if (!table) {
            throw new Error(`未找到表: ${name}`);
          }
          
          return {
            table
          };
        
        default:
          throw new Error(`未知操作: ${action}`);
      }
    } catch (error) {
      return {
        error: error.message
      };
    }
  }
}; 